<?php

namespace app\models;

use Yii;
use yii\db\Expression;
use yii\base\Exception;
/**
 * This is the model class for table "member".
 *
 * @property integer $id
 * @property string $name
 * @property string $tjr
 * @property string $tjm
 * @property string $push_tjm
 * @property string $push_tjm_create_time
 * @property integer $push_tjm_used
 * @property string $reg_date
 * @property double $nea_count
 * @property double $usd_count
 * @property string $phone
 * @property string $pw
 * @property integer $can_login
 * @property string $authkey
 * @property string $accesstoken
 * @property string $realname
 * @property string $sfzid
 * @property string $bankcardid
 * @property string $opencardbank
 * @property string $alipay
 * @property integer $status
 * @property integer $cur_tixian_count
 * @property integer $is_first_charge
 *
 * @property ChargeCashDeal[] $chargeCashDeals
 * @property MemberActivity[] $memberActivities
 * @property Message[] $messages
 * @property Message[] $messages0
 * @property Notice[] $notices
 */
class Member extends \yii\db\ActiveRecord implements \yii\web\IdentityInterface
{
  const STATUS_REGISTER=0;//等待审核的用户
  const STATUS_PROVED=1;  //已审核通过的合法用户
  const STATUS_UNPROVED=2;//未审核通过的非法用户

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'member';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'tjr', 'nea_count', 'usd_count', 'phone', 'pw', 'can_login', 'realname', 'sfzid', 'bankcardid', 'opencardbank', 'alipay'], 'required'],
            [['push_tjm_create_time', 'reg_date'], 'safe'],
            [['push_tjm_used', 'can_login', 'status', 'cur_tixian_count', 'is_first_charge'], 'integer'],
            [['nea_count', 'usd_count'], 'number'],
            [['name', 'tjr', 'realname', 'bankcardid', 'alipay'], 'string', 'max' => 30],
            [['tjm', 'pw', 'authkey', 'accesstoken'], 'string', 'max' => 32],
            [['push_tjm'], 'string', 'max' => 10],
            [['phone'], 'string', 'max' => 11],
            [['sfzid'], 'string', 'max' => 19],
            [['opencardbank'], 'string', 'max' => 64],
            [['name'], 'unique'],
            [['phone'], 'unique'],
            [['sfzid'], 'unique'],
            [['bankcardid'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
          'id' => 'ID',
          'name' => '会员名称',
          'tjr' => '推荐人用户名',
          'tjm' => '手持身份证',
          'push_tjm' => 'Push Tjm',
          'push_tjm_create_time' => 'Push Tjm Create Time',
          'push_tjm_used' => 'Push Tjm Used',
          'reg_date' => '注册日期',
          'nea_count' => 'NEA账户余额',
          'usd_count' => 'USD账户余额',
          'phone' => '手机号码',
          'pw' => '密码',
          'can_login' => '是否允许登录',
          'authkey' => '认证键',
          'accesstoken' => '访问令牌',
          'realname' => '真实姓名',
          'sfzid' => '身份证号码',
          'bankcardid' => '银行卡号',
          'opencardbank' => '开户行',
          'alipay' => '支付宝账号',
          'status' => 'Status',
          'cur_tixian_count' => '提现次数',
          'is_first_charge' => '首次充值',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getChargeCashDeals()
    {
        return $this->hasMany(ChargeCashDeal::className(), ['member_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getMemberActivities()
    {
        return $this->hasMany(MemberActivity::className(), ['member_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getMessages()
    {
        return $this->hasMany(Message::className(), ['receiver' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getMessages0()
    {
        return $this->hasMany(Message::className(), ['sender' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getNotices()
    {
        return $this->hasMany(Notice::className(), ['author' => 'id']);
    }
    /**
     * 添加会员，如果添加成功，再向member_activity表中添加一项注册活动
     * @return boolean
     */
    public function addMember($model)
    {
        $member=new Member;
        $member->name=$model->name;
        $member->tjr=$model->tjr;
        $member->tjm=$model->tjcode;
        $member->reg_date=new Expression('NOW()');
        $member->nea_count=0.0;
        $member->usd_count=0.0;
        $member->phone=$model->phone;
        $member->pw=md5($model->pw);
        $member->can_login=true;
        $member->realname=$model->realname;
        $member->sfzid=$model->sfzid;
        $member->bankcardid=$model->bankcardid;
        $member->opencardbank=$model->opencardbank;
        $member->alipay=$model->alipay;
        $member->status=0;//需要审核才能使用

        if(!$member->save()){
          var_dump($member->errors);
          exit;
          return false;
        }

        //设置推荐码失效
        /*if(!Member::setPushTjmUsed($model->tjr)){
          return false;
        }*/
        return true;
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    //public function changePW($model)
    public static function changePW($username,$newpw)
    {
      //$member = Member::find()->where(['name'=>$model->name])->one();
      $member = Member::find()->where(['name'=>$username])->one();
      if(is_null($member)){
        return false;
      }
      //$member->pw=md5($model->new_pw);
      $member->pw=md5($newpw);
      if(!$member->save()){
          //print_r($member->errors);
          //exit;
          return false;
      }
      return true;
    }

    /**
     * 改变单个用户的登录权限
     */
    public function changeLoginright($model)
    {
      $member = Member::find()->where(['name'=>$model->name])->one();
      if(is_null($member)){
        return false;
      }
      $member->can_login=$model->can_login;
      if(!$member->save()){
          //print_r($member->errors);
          //exit;
          return false;
      }
      return true;
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public static function changeProfile($id,$realname,$sfzid,$bankcardid,$opencardbank,$alipay)
    {
      $member = Member::findOne($id);
      if(is_null($member)){
        return false;
      }
      $member->realname=$realname;
      $member->sfzid=$sfzid;
      $member->bankcardid=$bankcardid;
      $member->opencardbank=$opencardbank;
      $member->alipay=$alipay;

      if(!$member->save()){
          //print_r($member->errors);
          //exit;
          return false;
      }
      return true;
    }

    ////////////////////////////////////////////////////////////////////////////////////////////////////////
    // IdentityInterface implements
    ////////////////////////////////////////////////////////////////////////////////////////////////////////
    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
      return static::findOne($id);
    }

    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
      return static::findOne(['access_token' => $token]);
    }
    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->authkey;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->authkey === $authKey;
    }

    /**
     * Finds user by username
     *
     * @param  string      $username
     * @return static|null
     */
    public static function findByMemberName($username)
    {
        $user = Member::find()
            ->where(['name' => $username])
            ->asArray()
            ->one();
        if($user){
            return new static($user);
        }
        return null;
    }

    /**
     * 查找用户名
     *
     * @param  string      $username
     * @return static|null
     */
    public static function findByMemberName2($username)
    {
        $user = Member::find()
            ->where(['name' => $username])
            ->one();
        if($user){
            return $user;
        }
        return null;
    }

    /**
     * Validates password
     *
     * @param string $password password to validate
     * @return bool if password provided is valid for current user
     */
    public function validatePassword($password)
    {
        return $this->pw === md5($password);
    }
    /**
     * Generates "remember me" authentication key
     */
    public function generateAuthKey()
    {
        $this->authkey = Yii::$app->security->generateRandomString();
    }

    public function attributeValues()
    {
    	return [
    		'can_login' => [
    			'0' => '禁止登录',
    			'1' => '允许登录',
    		],
    	];
    }

    /**
     * 生成tjm(10位推荐码)
     */
    public static function generatePushTjm(){
        srand((double)microtime()*1000000);//create a random number feed.
        $ychar="0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";  // 36;
        $list=explode(",",$ychar);
        $authnum='';
        for($i=0;$i<10;$i++){
          $randnum=rand(0,35); //0,35
          $authnum.=$list[$randnum];
        }
        return $authnum;
    }

    /**
     * 生成rand
     */
    public static function generateRandom($len){
        srand((double)microtime()*1000000);//create a random number feed.
        $ychar="0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";  // 36;
        $list=explode(",",$ychar);
        $authnum='';
        for($i=0;$i<$len;$i++){
          $randnum=rand(0,35); //0,35
          $authnum.=$list[$randnum];
        }
        return $authnum;
    }
    /**
     * 请求一个tjm(10位推荐码)来推荐他人注册
     */
    public static function requestPushTjm(){
      $tjm=[];
      $expireTime=7*24*3600;
      if(Yii::$app->user->isGuest){
        return $tjm;
      }else{
        $member=Member::findOne(Yii::$app->user->getId());
        if(is_null($member)){
          return $tjm;
        }
        $time = time();//以秒计
        $create_time = strtotime($member->push_tjm_create_time);
        if(($time > ($create_time + $expireTime))||($member->push_tjm_used===1)){
          $new_push_tjm = self::generatePushTjm();
          $member->push_tjm_create_time=new Expression("NOW()");
          $member->push_tjm=$new_push_tjm;
          $member->push_tjm_used=0;
          if(!$member->save()){
            return $tjm;
          }
          $tjm['push_tjm']=$new_push_tjm;
          $tjm['create_time']=date("Y-m-d H:i:s",$time);
          return $tjm;
        }
        $tjm['push_tjm']=$member->push_tjm;
        $tjm['create_time']=$member->push_tjm_create_time;

        return $tjm;
      }
    }
    /**
     * 请求一个tjm(10位推荐码)来推荐他人注册
     */
    public static function setPushTjmUsed($username){
      $member=Member::find()->where(
        ['name' => $username]
        )->One();
      if(is_null($member)){
        return;
      }
      $member->push_tjm_used=1;
      if(!$member->save()){
        //print_r($member->errors);
        //exit;
        return false;
      }
      return true;
    }
    /**
     * 更新当前提现数目
     */
    public static function updateCurTixianCount($id,$count){
      $model=Member::findOne($id);
      if(is_null($model)){
        return false;
      }
      $model->cur_tixian_count=$count;
      if(!$model->save()){
        return false;
      }
      return true;
    }

    /**
     * 修改用户信息
     */
    public static function updateMemberInfo($model){
      $user=Member::findOne($model->id);
      if(is_null($user)){
        return false;
      }
      $user->alipay=$model->alipay;
      $user->sfzid=$model->sfzid;
      $user->bankcardid=$model->bankcardid;
      $user->opencardbank=$model->opencardbank;
      $user->name=$model->name;
      $user->realname=$model->realname;
      $user->phone=$model->phone;

      if(!$user->save()){
        return false;
      }
      return true;
    }

    /**
     * 功能：修改多个用户的登录权限
     * 参数：$keys：选中的用户
     *      $mode：操作模式 'forbid'       禁止keys所指定的用户登录
     *                     'forbidall'    禁止所有用户登录
     *                     'unforbid'     允许keys所指定的用户登录
     *                     'unforbidall'  允许所有用户登录
     */
    public static function forbidUsers($keys,$mode){
      switch($mode){
        case 'forbid':
          return Member::updateAll(['can_login'=>0],['id'=>$keys]);
          break;
        case 'forbidall':
          return Member::updateAll(['can_login'=>0],"id <> ".Yii::$app->user->getId());
          break;
        case 'unforbid':
          return Member::updateAll(['can_login'=>1],['id'=>$keys]);
          break;
        case 'unforbidall':
          return Member::updateAll(['can_login'=>1],"id <> ".Yii::$app->user->getId());
          break;
        default:
          return false;
          break;
      }
    }

    /**
     * 功能：审核用户
     */
    public static function proveUser($id,$pass){
      $model=Member::findOne($id);
      if(is_null($model)){
        return false;
      }
      if($model->status!=Member::STATUS_REGISTER){
        return false;
      }
      if(1==$pass){
          $model->status=Member::STATUS_PROVED;
      }else if(0==$pass){
          $model->status=Member::STATUS_UNPROVED;
      }else{
        return false;
      }
      if(!$model->save()){
        return false;
      }
      return true;

    }

    /**
     * 功能：删除待审核的注册用户和审核不通过的注册
     */
    public static function delRegUser($keys){
      //1.取消外键约束
      $cmd1 = Yii::$app->db->createCommand('SET FOREIGN_KEY_CHECKS=0');
      $cmd1->execute();
      if(!Member::deleteAll(['id'=>$keys])){
        //2.恢复外键约束
        $cmd2 = Yii::$app->db->createCommand('SET FOREIGN_KEY_CHECKS=1');
        $cmd2->execute();
        return false;
      }
      //2.恢复外键约束
      $cmd2 = Yii::$app->db->createCommand('SET FOREIGN_KEY_CHECKS=1');
      $cmd2->execute();
      return true;

    }

    /**
     * 功能：资金互转计算
     */
     public static function zijinHuzhuan($id,$type,$money){
       $model=Member::findOne($id);
       if(is_null($model)){
         return false;
       }
       if($type==ChargeCashDeal::TYPE_NEA_USD){
         if($model->nea_count < $money){
           //nea账户金额不足，无法转出
           throw new Exception('基金账户金额不足，无法转出');
           return false;
         }
         if($money>$model->nea_count*0.7){
           //一次最多只能转出基金账户的70%
           throw new Exception('一次最多只能转出基金账户的70%');
           return false;
         }

        $model->nea_count-=$money;
        $model->usd_count+=$money;

       }else if($type==ChargeCashDeal::TYPE_USD_NEA){
         if($model->usd_count < $money){
           //usd账户金额不足，无法转出
           throw new Exception('个人账户金额不足，无法转出');
           return false;
         }

         $model->usd_count-=$money;
         $model->nea_count+=$money;

       }else{
         return false;
       }

       if(!$model->save()){
         return false;
       }

       return true;

     }
     /**
      * 功能：充值划拨
      */
      public static function congzhi($userid,$money){
        $model=Member::findOne($userid);
        if(is_null($model)){
          return false;
        }
        $model->usd_count=$model->usd_count+$money;
        if(!$model->save()){
            return false;
        }

        return true;

      }

      /**
       * 功能：是否首次充值
       */
       public static function isFirstCharge($userid){
         $model=Member::findOne($userid);
         if(is_null($model)){
           return false;
         }
         if(1==$model->is_first_charge){
           return true;
         }
         return false;

       }


      /**
       * 功能：提现划拨
       */
       public static function tixian($userid,$money,$istry){
         $model=Member::findOne($userid);
         if(is_null($model)){
           return false;
         }

         //对提现金额进行校验
         if($model->usd_count<$money){
           throw new Exception('个人账户余额不足');
           return false;
         }
         if($istry){
           return true;
         }
         $model->usd_count=$model->usd_count-$money;
         if(!$model->save()){
             return false;
         }

         return true;

       }

       /**
        * 功能：提现金额预判，提现金额超过70%失败
        * money:单位 美元
        */
       public static function tixianJudge($userid,$money,$exchangerate){
         $model=Member::findOne($userid);
         if(is_null($model)){
           return false;
         }

         //对提现金额进行校验 70%;
         $limit = $model->usd_count*0.7;
         $usdmoney = $money/$exchangerate;
         if($limit<$usdmoney){
           return false;
         }
         return true;

       }


       /**
        * 功能：分红
        */
        public static function fenhong($user,$fenhong_val){
          if(is_null($user)){
            return false;
          }
          $user->usd_count=$user->usd_count+$fenhong_val;
          if(!$user->save()){
              return false;
          }

          return true;

        }

        /**
         * 功能：七代
         */
         public static function seven($user,$seven_reward){
           if(is_null($user)){
             return false;
           }
           $user->usd_count=$user->usd_count+$seven_reward;
           if(!$user->save()){
               return false;
           }

           return true;

         }
         /**
          * 功能：推荐奖（被推荐人首次充值时计算）
          */
          public static function tuijian($user,$tuijian_reward){
            if(is_null($user)){
              return false;
            }
            $user->usd_count=$user->usd_count+$tuijian_reward;
            if(!$user->save()){
                return false;
            }

            return true;

          }
}
